上期答案
问题1. 给出如下函数:
11. public static int sum(List list) {
12. int sum = 0;
13. for ( Iterator iter = list.iterator();iter.hasNext(); ) {
14. int i =((Integer)iter.next()).intValue();
15. sum += i;
16. }
17. return sum;
18. }
请在下列选项中选出三个改动,使得函数可以使用泛型且不会提示泛型未检测警告?
(Choose three.)
A. Remove line 14.
B. Replace line 14 with "int i =iter.next();".
C. Replace line 13 with "for (int i : intList){".
D. Replace line 13 with "for (Iterator iter :intList) {".
E. Replace the method declaration with"sum(List<int> intList)".
F. Replace the method declaration with"sum(List<Integer> intList)".
答案 A C F
知识点:
1. 在JAVA的泛型中不能使用基本数据类型
2. 使用迭代器遍历容器
遍历容器的三种方式
List<String> userlist = newArrayList<String>();
userlist.add(“aa");
userlist.add(“bb");
userlist.add(“cc");
//使用普通for循环
for(int i=0; i<userlist.size(); i++){ }
//使用Iterator迭代器
Iterator it = userlist.iterator();
while(it.hasNext()){ }
for (;it.hasNext();it.next() ){ }
//使用增强for循环
for(String s : userlist){ }
问题2:在算法中要求使用java.util.List数据结构,该算法要求可以方便的添加“add”一个元素,但是不要求支持随机快速访问元素,请问你会选择下列的那个类?
A. java.util.Queue
B. java.util.ArrayList
C. java.util.Li